<template>
  <div class="data-upload">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据导入</span>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="身份信息导入" name="identity">

          <!-- 模板下载提示 -->
          <el-alert
            title="模板说明"
            type="info"
            :closable="false"
            style="margin-bottom: 20px;">
            <template #default>
              <div>
                <p>请按照标准模板格式填写Excel文件，确保表头和数据格式正确。</p>
                <el-button type="primary" size="small" @click="downloadTemplate('identity')" style="margin-top: 10px;">
                  下载身份信息模板
                </el-button>
              </div>
            </template>
          </el-alert>
          
          <div class="upload-demo">
            <el-upload
              ref="identityUploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :limit="maxFileCount"
              accept=".xlsx,.xls">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传xlsx/xls文件，且不超过10MB
                </div>
              </template>
            </el-upload>
            <el-button 
              type="primary" 
              :disabled="!selectedFile || !isIdentityFormValid" 
              @click="handleManualUpload"
              :loading="uploadLoading"
              style="margin-top: 20px;">
              {{ uploadLoading ? '上传中...' : '开始上传' }}
            </el-button>
          </div>
        </el-tab-pane>

        <el-tab-pane label="收入信息导入" name="income">
          <!-- 收入信息导入表单 -->
          <el-form :model="incomeForm" label-width="120px" style="margin-bottom: 20px;">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="季度选择">
                  <el-select v-model="incomeForm.quarter" placeholder="请选择季度" style="width: 100%" @change="handleQuarterChange">
                    <el-option
                        v-for="quarterOption in quarterOptions"
                        :key="quarterOption.value"
                        :label="quarterOption.label"
                        :value="quarterOption.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="收入所属期起">
                  <el-date-picker
                      v-model="incomeForm.startTime"
                      type="date"
                      placeholder="选择开始日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收入所属期止">
                  <el-date-picker
                      v-model="incomeForm.endTime"
                      type="date"
                      placeholder="选择结束日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 模板下载提示 -->
          <el-alert
              title="模板说明"
              type="info"
              :closable="false"
              style="margin-bottom: 20px;">
            <template #default>
              <div>
                <p>请按照标准模板格式填写Excel文件，确保表头和数据格式正确。</p>
                <el-button type="primary" size="small" @click="downloadTemplate('income')" style="margin-top: 10px;">
                  下载收入信息模板
                </el-button>
              </div>
            </template>
          </el-alert>

          <div class="upload-demo">
            <el-upload
                ref="incomeUploadRef"
                class="upload-demo"
                drag
                :auto-upload="false"
                :on-change="handleFileChange"
                :before-upload="beforeUpload"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :limit="maxFileCount"
                accept=".xlsx,.xls">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传xlsx/xls文件，且不超过10MB
                </div>
              </template>
            </el-upload>
            <el-button
                type="primary"
                :disabled="!selectedFile || !isIncomeFormValid"
                @click="handleManualUpload"
                :loading="uploadLoading"
                style="margin-top: 20px;">
              {{ uploadLoading ? '上传中...' : '开始上传' }}
            </el-button>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="平台信息导入" name="platform">
          <!-- 模板下载提示 -->
          <el-alert
            title="模板说明"
            type="info"
            :closable="false"
            style="margin-bottom: 20px;">
            <template #default>
              <div>
                <p>请按照标准模板格式填写Excel文件，确保表头和数据格式正确。</p>
                <el-button type="primary" size="small" @click="downloadTemplate('platform')" style="margin-top: 10px;">
                  下载平台信息模板
                </el-button>
              </div>
            </template>
          </el-alert>
          
          <div class="upload-demo">
            <el-upload
              ref="platformUploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :limit="maxFileCount"
              accept=".xlsx,.xls">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传xlsx/xls文件，且不超过10MB
                </div>
              </template>
            </el-upload>
            <el-button 
              type="primary" 
              :disabled="!selectedFile || !isPlatformFormValid" 
              @click="handleManualUpload"
              :loading="uploadLoading"
              style="margin-top: 20px;">
              {{ uploadLoading ? '上传中...' : '开始上传' }}
            </el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 导入结果弹窗 -->
    <el-dialog v-model="importResultVisible" title="导入结果" width="700px" :close-on-click-modal="false">
      <div v-if="importResult">
        <el-result
          :icon="importResult.success ? 'success' : 'error'"
          :title="importResult.message">
          
          <template #extra>
            <!-- 详细统计信息 -->
            <div class="statistics-details" v-if="importResult.totalCount > 0">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-statistic title="总记录数" :value="importResult.totalCount || 0"/>
                </el-col>
                <el-col :span="8">
                  <el-statistic title="成功数量" :value="importResult.successCount || 0" value-style="color: #67c23a"/>
                </el-col>
                <el-col :span="8">
                  <el-statistic title="失败数量" :value="importResult.failCount || 0" value-style="color: #f56c6c"/>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-result>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="importResult?.failCount > 0 && errorMessages && errorMessages.length > 0" 
                     type="primary" 
                     @click="showErrorDetails"
                     style="margin-right: 10px;">
            查看详细错误 ({{ errorMessages.length }})
          </el-button>
          <el-button type="danger" @click="closeResultDialogAndRefresh">
            关闭
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 错误详情对话框 -->
    <el-dialog v-model="errorDialogVisible" title="错误详情" width="60%">
      <div v-if="errorMessages && errorMessages.length > 0">
        <el-alert
          title="导入过程中发现以下错误："
          type="error"
          :closable="false"
          style="margin-bottom: 20px;">
        </el-alert>
        
        <el-table :data="errorMessages" style="width: 100%" border stripe>
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="message" label="错误信息" min-width="400" show-overflow-tooltip>
            <template #default="scope">
              <span style="color: #f56c6c;">{{ scope.row.message || scope.row }}</span>
            </template>
          </el-table-column>
        </el-table>
        
        <div style="margin-top: 20px; text-align: center;">
          <el-button @click="errorDialogVisible = false">关闭</el-button>
        </div>
      </div>
      
      <div v-else style="text-align: center; padding: 40px;">
        <el-empty description="暂无错误信息" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { excelApi } from '../api/excel'
import { useUserStore } from '../stores/user'

// 用户状态
const userStore = useUserStore()

// 基础状态
const activeTab = ref('identity')
const importResult = ref(null)
const errorDialogVisible = ref(false)
const errorMessages = ref([])
const uploadLoading = ref(false)
const selectedFile = ref(null)
const importResultVisible = ref(false)

// 文件上传相关
const incomeUploadRef = ref(null)
const identityUploadRef = ref(null)
const platformUploadRef = ref(null)

// 表单数据
const incomeForm = ref({
  quarter: '1',
  startTime: '',
  endTime: '',
  reportDate: ''
})

const identityForm = ref({
  reportDate: ''
})

const platformForm = ref({
  reportDate: ''
})

// 计算属性
const isIncomeFormValid = computed(() => {
  return incomeForm.value.quarter && 
         incomeForm.value.startTime && 
         incomeForm.value.endTime && 
         incomeForm.value.reportDate
})

const isIdentityFormValid = computed(() => {
  return identityForm.value.reportDate
})

const isPlatformFormValid = computed(() => {
  return platformForm.value.reportDate
})

// 动态生成季度选项
const quarterOptions = computed(() => {
  const options = []
  const now = new Date()
  const currentYear = now.getFullYear()
  
  // 生成近两年的季度选项
  for (let year = currentYear - 1; year <= currentYear + 1; year++) {
    for (let quarter = 1; quarter <= 4; quarter++) {
      const quarterNames = ['', '第一季度', '第二季度', '第三季度', '第四季度']
      const monthRanges = ['', '1月-3月', '4月-6月', '7月-9月', '10月-12月']
      
      options.push({
        value: `${year}-${quarter}`,
        label: `${year}年${quarterNames[quarter]} (${monthRanges[quarter]})`
      })
    }
  }
  
  return options
})


// 生命周期钩子 - 放在变量声明之后
onMounted(() => {
  initDefaultTimes()
})

// 文件数量限制
const maxFileCount = 1

// 方法定义
const initDefaultTimes = () => {
  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth() + 1
  
  // 计算上一季度
  let lastQuarter = Math.ceil(currentMonth / 3) - 1
  let lastQuarterYear = currentYear
  if (lastQuarter === 0) {
    lastQuarter = 4
    lastQuarterYear = currentYear - 1
  }
  
  // 设置收入信息默认时间，使用新的季度格式
  incomeForm.value.quarter = `${lastQuarterYear}-${lastQuarter}`
  const { startTime, endTime } = getQuarterTime(lastQuarterYear, lastQuarter)
  incomeForm.value.startTime = startTime
  incomeForm.value.endTime = endTime
  incomeForm.value.reportDate = formatDate(now)
  
  // 设置身份信息和平台信息默认时间
  identityForm.value.reportDate = formatDate(now)
  platformForm.value.reportDate = formatDate(now)
}

const getQuarterTime = (year, quarter) => {
  const startMonth = (quarter - 1) * 3 + 1
  const endMonth = quarter * 3
  
  const startDate = new Date(year, startMonth - 1, 1)
  const endDate = new Date(year, endMonth, 0) // 获取月末
  
  return {
    startTime: formatDate(startDate),
    endTime: formatDate(endDate)
  }
}

const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const handleQuarterChange = () => {
  // 解析季度值，格式为 "年份-季度"
  const [year, quarter] = incomeForm.value.quarter.split('-').map(Number)
  const { startTime, endTime } = getQuarterTime(year, quarter)
  incomeForm.value.startTime = startTime
  incomeForm.value.endTime = endTime
}

const handleTabClick = (tab) => {
  // 清空之前选择的文件
  selectedFile.value = null
  // 清空上传组件显示的文件
  if (tab.paneName === 'income') {
    incomeUploadRef.value?.clearFiles()
  } else if (tab.paneName === 'identity') {
    identityUploadRef.value?.clearFiles()
  } else if (tab.paneName === 'platform') {
    platformUploadRef.value?.clearFiles()
  }
  // 重置导入结果
  importResult.value = null
  // 关闭导入结果弹窗
  importResultVisible.value = false
  // 关闭错误详情弹窗
  errorDialogVisible.value = false
  // 重置上传状态
  uploadLoading.value = false
  // 重置表单数据
  resetFormData()
}

const resetFormData = () => {
  // 重置收入信息表单
  incomeForm.value = {
    quarter: '2024-4', // 使用新的季度格式，默认2024年第四季度
    startTime: '',
    endTime: '',
    reportDate: ''
  }
  
  // 重置身份信息表单
  identityForm.value = {
    reportDate: ''
  }
  
  // 重置平台信息表单
  platformForm.value = {
    reportDate: ''
  }
  
  // 重新初始化默认时间
  initDefaultTimes()
}

const handleFileChange = (file) => {
  // 文件选择时，如果已经有一个文件，则替换它
  if (selectedFile.value) {
    selectedFile.value = file.raw
  } else {
    selectedFile.value = file.raw
  }
}

const beforeUpload = (file) => {
  // 检查文件类型
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！')
    return false
  }
  
  // 检查文件大小（限制为10MB）
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB！')
    return false
  }
  
  // 只允许一个文件
  selectedFile.value = file
  return false // 阻止自动上传，使用手动上传
}

const handleRemove = () => {
  selectedFile.value = null
}

const handleExceed = (files) => {
  ElMessage.warning(`最多只能上传${maxFileCount}个文件`)
}

const downloadTemplate = async (type) => {
  try {
    // 使用API方法下载模板，确保携带JWT token
    const response = await excelApi.downloadTemplate(type)
    
    // 创建Blob对象
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 设置文件名
    let fileName = ''
    switch (type) {
      case 'income':
        fileName = '收入信息导入模板.xlsx'
        break
      case 'identity':
        fileName = '身份信息导入模板.xlsx'
        break
      case 'platform':
        fileName = '平台信息导入模板.xlsx'
        break
      default:
        fileName = '模板.xlsx'
    }
    
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 释放URL对象
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败，请检查网络连接或重新登录')
  }
}

const handleManualUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.error('请先选择文件')
    return
  }

  // 验证表单
  if (activeTab.value === 'income' && !isIncomeFormValid.value) {
    ElMessage.error('请填写完整的收入信息')
    return
  }
  if (activeTab.value === 'identity' && !isIdentityFormValid.value) {
    ElMessage.error('请填写上报日期')
    return
  }
  if (activeTab.value === 'platform' && !isPlatformFormValid.value) {
    ElMessage.error('请填写上报日期')
    return
  }

  try {
    uploadLoading.value = true
    const userId = userStore.userInfo?.id || 1

    let response
    switch (activeTab.value) {
      case 'income':
        response = await excelApi.importIncomeExcel(selectedFile.value, userId, incomeForm.value)
        break
      case 'identity':
        response = await excelApi.importIdentityExcel(selectedFile.value, userId, identityForm.value)
        break
      case 'platform':
        response = await excelApi.importPlatformExcel(selectedFile.value, userId, platformForm.value)
        break
      default:
        ElMessage.error('未知的导入类型')
        return
    }
    // 清理文件
    selectedFile.value = null
    // 清空上传组件显示的文件
    if (activeTab.value === 'income') {
      incomeUploadRef.value?.clearFiles()
    } else if (activeTab.value === 'identity') {
      identityUploadRef.value?.clearFiles()
    } else if (activeTab.value === 'platform') {
      platformUploadRef.value?.clearFiles()
    }

    // 上传成功
    if (response.data.success) {
      ElMessage.success(response.data.message)
      
      console.log('上传响应数据：', response.data)
      
      // 显示导入结果
      importResult.value = {
        success: response.data.success,
        message: response.data.message,
        totalCount: response.data.totalCount,
        successCount: response.data.successCount,
        failCount: response.data.failCount,
        errorMessages: response.data.errorMessages || []
      }
      
      console.log('设置的导入结果：', importResult.value)
      
      // 准备错误信息，确保数据结构正确
      if (response.data.failCount > 0 && response.data.errorMessages) {
        // 如果errorMessages是字符串数组，直接使用
        if (Array.isArray(response.data.errorMessages)) {
          errorMessages.value = response.data.errorMessages
        } else {
          // 如果不是数组，转换为数组格式
          errorMessages.value = [response.data.errorMessages]
        }
        console.log('设置错误信息：', errorMessages.value)
        console.log('错误信息类型：', typeof response.data.errorMessages)
        console.log('错误信息是否为数组：', Array.isArray(response.data.errorMessages))
      } else {
        errorMessages.value = []
        console.log('没有错误信息或失败数量为0')
      }
      
      // 显示导入结果弹窗
      importResultVisible.value = true
    } else {
      ElMessage.error(response.data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('文件上传失败！')
    console.error('Upload error:', error)
  } finally {
    uploadLoading.value = false
  }
}

const showErrorDetails = () => {
  console.log('显示错误详情，错误信息：', errorMessages.value)
  console.log('错误信息长度：', errorMessages.value?.length)
  console.log('错误信息类型：', typeof errorMessages.value)
  console.log('是否为数组：', Array.isArray(errorMessages.value))
  
  // 确保有错误信息时才显示错误详情弹窗
  if (errorMessages.value && errorMessages.value.length > 0) {
    errorDialogVisible.value = true
  } else {
    ElMessage.warning('暂无错误详情信息')
    console.warn('errorMessages为空或长度为0')
  }
}

const closeResultDialogAndRefresh = () => {
  importResultVisible.value = false;
  // 刷新页面或重新加载数据
  window.location.reload();
};


</script>

<style scoped>
.data-upload {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-demo {
  text-align: center;
}

.el-upload__tip {
  color: #909399;
}

/* 弹窗内容样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-result__title) {
  font-size: 18px;
  margin-bottom: 10px;
}

:deep(.el-result__subtitle) {
  font-size: 14px;
  color: #606266;
  margin-bottom: 20px;
}

.statistics-details {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.statistics-details .el-statistic {
  text-align: center;
}

.statistics-details .el-statistic__title {
  font-size: 14px;
  color: #606266;
}

.statistics-details .el-statistic__number {
  font-size: 24px;
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-divider {
  margin: 30px 0;
}
</style>
